package com.xja.service.impl;

import com.xja.common.JsonBean;
import com.xja.entity.SysDept;
import com.xja.entity.SysRole;
import com.xja.entity.SysStaff;
import com.xja.mapper.SysDeptMapper;
import com.xja.mapper.SysRoleMapper;
import com.xja.mapper.SysStaffMapper;
import com.xja.service.SysDeptService;
import com.xja.service.SysStaffService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2024-01-15 10:54
 */
@Service
public class SysStaffServiceImpl implements SysStaffService {

    @Autowired
    private SysStaffMapper sysStaffMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public JsonBean selectList() {
        return new JsonBean(0, "ok", sysStaffMapper.selectList());
    }

    @Override
    public JsonBean selectById(Integer id) {
        SysStaff sysStaff = sysStaffMapper.selectByPrimaryKey(id);
        Map<String, Object> map = new HashMap<>();
        map.put("sysStaff",sysStaff);
        List<SysDept> deptList = sysDeptMapper.selectTreeList();
        map.put("deptList",deptList);
        List<SysRole> sysRoleList = sysRoleMapper.getListByDeptId(Integer.valueOf(sysStaff.getDeptId()));
        map.put("sysRoleList",sysRoleList);
        return new JsonBean(0, "ok", map);
    }

    @Override
    public JsonBean deleteById(Integer id) {
        JsonBean jsonBean = new JsonBean(-1, "fail", null);
        int i = sysStaffMapper.deleteByPrimaryKey(id);
        if(i>0){
            jsonBean = new JsonBean(0, "ok", null);
        }
        return jsonBean;
    }

    @Override
    public JsonBean insertStaff(SysStaff sysStaff) {
        JsonBean jsonBean = new JsonBean(-1, "该手机号已存在", null);
        SysStaff dbStaff = sysStaffMapper.selectBytelephone(sysStaff.getTelephone());
        if(dbStaff == null){
            jsonBean = new JsonBean(-999, "系统异常", null);
            sysStaff.setLoginName(sysStaff.getTelephone());
            sysStaff.setSalt(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16));
            sysStaff.setPassword(DigestUtils.md5Hex(DigestUtils.md5Hex("123456") + sysStaff.getSalt()));
            int i = sysStaffMapper.insert(sysStaff);
            if(i>0){
                jsonBean = new JsonBean(0, "ok", null);
            }
        }

        return jsonBean;
    }

    @Override
    public JsonBean updateStaff(SysStaff sysStaff) {
        JsonBean jsonBean = new JsonBean(-1, "fail", null);
        int i = sysStaffMapper.updateByPrimaryKeySelective(sysStaff);
        if(i>0){
            jsonBean = new JsonBean(0, "ok", null);
        }
        return jsonBean;
    }
}
